package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.bean.User_Information;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.Utils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.Circle_ImageView;
import com.jaya.budan.views.CommonPopWindow;
import com.jaya.budan.views.CustomDatePicker;
import com.jaya.budan.views.PickerScrollView;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class Fill_Information_Activity extends BaseActivity implements View.OnClickListener, CommonPopWindow.ViewClickListener {

    private EditText et_fill_nicheng;
    private Button btn_fill_informat_next;
    private RelativeLayout rl_fill_bron, rl_fill_height, rl_fill_weight;
    private TextView tv_fill_bron, tv_fill_height, tv_fill_weight;
    private RadioGroup rg_fill;
    private Circle_ImageView iv_fill_information_icon;
    private CustomDatePicker customDatePicker;
    private String now, height = "170cm", weight = "65kg", time_bron = "1990-01-01", access_token;
    private int sex = 1;
    private long exitTime = 0;
    private User_Information user_information;
//    private Region region = new Region(this.region);//设置存储桶所在的地区
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fill_information);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        rl_fill_bron = findViewById(R.id.rl_fill_bron);
        rl_fill_height = findViewById(R.id.rl_fill_height);
        rl_fill_weight = findViewById(R.id.rl_fill_weight);
        et_fill_nicheng = findViewById(R.id.et_fill_nicheng);
        tv_fill_bron = findViewById(R.id.tv_fill_bron);
        tv_fill_height = findViewById(R.id.tv_fill_height);
        tv_fill_weight = findViewById(R.id.tv_fill_weight);
        iv_fill_information_icon = findViewById(R.id.iv_fill_information_icon);
        rg_fill = findViewById(R.id.rg_fill);
        btn_fill_informat_next = findViewById(R.id.btn_fill_informat_next);
        btn_fill_informat_next.setOnClickListener(this);
        rl_fill_bron.setOnClickListener(this);
        rl_fill_height.setOnClickListener(this);
        rl_fill_weight.setOnClickListener(this);
        iv_fill_information_icon.setOnClickListener(this);
        et_fill_nicheng.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count > 0){
                    btn_fill_informat_next.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        postData(1);//通过性别来获取数据
        rg_fill.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.male){
                    ToolUtils.showToast(Fill_Information_Activity.this, "男");
                    sex = 1;
                } else {
                    ToolUtils.showToast(Fill_Information_Activity.this, "女");
                    sex = 2;
                    postData(sex);//通过性别来获取数据
                }
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_fill_informat_next:
                if (ToolUtils.isEmpty(et_fill_nicheng.getText().toString().trim())){
                    ToolUtils.showToast(this, "昵称不能为空");
                } else {
                    Intent intent = new Intent(Fill_Information_Activity.this, Fill_Information2_Activity.class);
                    intent.putExtra("nicename", et_fill_nicheng.getText().toString().trim());
                    intent.putExtra("sex", sex);
                    intent.putExtra("birthday", time_bron);
                    intent.putExtra("height", height);
                    intent.putExtra("weigh", weight);
                    intent.putExtra("access_token", access_token);
                    intent.putExtra("user_information", user_information);
                    startActivity(intent);
                }
                break;
            case R.id.iv_fill_information_icon:
                Intent intent = new Intent(this, PhotoAlbum_Activity.class);
                intent.putExtra("access_token", access_token);
                intent.putExtra("bucket", "head");
                intent.putExtra("cos_type", 0);
                startActivity(intent);
                break;
            case R.id.rl_fill_bron:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                now = sdf.format(new Date());//获取当前时间
                //tvElectricalTime.setText(now.split(" ")[0]);
                customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        time_bron = time.substring(0, 10);
                        Log.d("yyyyy", time_bron);
                        tv_fill_bron.setVisibility(View.VISIBLE);
                        tv_fill_bron.setText("" + time_bron);
                    }
                }, "1960-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                customDatePicker.show(now);//显示当前时间
                break;
            case R.id.rl_fill_height:
                int screenHeigh = getResources().getDisplayMetrics().heightPixels;//获取全屏高度
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_picker_selector_bottom)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 600)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsCenter(v);
                break;
            case R.id.rl_fill_weight:
                CommonPopWindow.newBuilder()
                        .setView(R.layout.pop_picker_selector_bottom)
                        .setAnimationStyle(R.style.AnimUp)
                        .setBackgroundDrawable(new BitmapDrawable())
                        .setSize(0, 600)
                        .setViewOnClickListener(this)
                        .setBackgroundDarkEnable(true)
                        .setBackgroundAlpha(0.7f)
                        .build(this)
                        .showAsCenter(v);
                break;
            default:
                break;
        }
    }

    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_picker_selector_bottom:
                TextView imageBtn = view.findViewById(R.id.img_guanbi);
                TextView tv_cancle = view.findViewById(R.id.tv_cancle);
                PickerScrollView addressSelector = view.findViewById(R.id.address);
                PickerScrollView addressSelector2 = view.findViewById(R.id.address2);
                // 设置数据，默认选择第一条
                final List<String> list = new ArrayList();
                if (user_information != null) {
                    for (int i=0; i<user_information.getHeight().size(); i++){
                        list.add(user_information.getHeight().get(i).toString() + "cm");
                    }
                }
                addressSelector.setData(list);
//                addressSelector.setSelected(0);
                addressSelector.setSelected("160cm");
                height = "160cm";
                //滚动监听
                addressSelector.setOnSelectListener(new PickerScrollView.onSelectListener() {
                    @Override
                    public void onSelect(String pickers) {
                        height = pickers;
                        tv_fill_height.setVisibility(View.VISIBLE);
                        tv_fill_height.setText("" + height);
                    }
                });
                // 设置数据，默认选择第一条
                final List<String> list2 = new ArrayList();
                if (user_information != null) {
                    for (int i=0; i<user_information.getWeigh().size(); i++){
                        list2.add(user_information.getWeigh().get(i).toString() + "kg");
                    }
                }
                addressSelector2.setData(list2);
                addressSelector2.setSelected("60kg");
                weight = "60kg";
                //滚动监听
                addressSelector2.setOnSelectListener(new PickerScrollView.onSelectListener() {
                    @Override
                    public void onSelect(String pickers) {
                        weight = pickers;
                        tv_fill_weight.setVisibility(View.VISIBLE);
                        tv_fill_weight.setText("" + weight);
                    }
                });
                //完成按钮
                imageBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        Log.d("yyyyy", height + weight);
                        tv_fill_height.setVisibility(View.VISIBLE);
                        tv_fill_height.setText("" + height);
                        tv_fill_weight.setVisibility(View.VISIBLE);
                        tv_fill_weight.setText("" + weight);
                    }
                });
                tv_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        height = "";
                        weight = "";
                        tv_fill_height.setVisibility(View.INVISIBLE);
                        tv_fill_weight.setVisibility(View.INVISIBLE);
                    }
                });
                break;
        }
    }

    /**
     * 网络请求
     */
    private void postData(int sex) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.User_Choose_information_Url + access_token + "&sex=" + sex + "&client=1", null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("fill_information", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        user_information = gson.fromJson(info.toString(), User_Information.class);
                    } else {
                        ToolUtils.showToast(Fill_Information_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Fill_Information_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        SharedPreferences preferences = getSharedPreferences("photo_path", Context.MODE_PRIVATE);
        JSONObject object = new JSONObject();
        //直接用选择的文件URI去展示图片
        //如果所选文件不是图片文件，则展示文件图标
        try{
            object.put("type", "head");
            object.put("path", preferences.getString("path", ""));
            object.put("p_id", 0);
            object.put("sort", 1);
        } catch (Exception e){
            e.printStackTrace();
        }
        if (preferences.getString("path", "").equals("")){
            ToolUtils.showToast(Fill_Information_Activity.this, "path~");
        } else {
            postImgData(object);//头像图片获取
        }
    }

    /**
     * 网络请求
     * @param object
     */
    private void postImgData(JSONObject object) {
        Log.d("fill_information", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.fill_information_icon_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("fill_information", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        String path = info.getString("path");//图片cos访问地址
                        Glide.with(Fill_Information_Activity.this).load(path).apply(new RequestOptions()
                                .placeholder(R.mipmap.fill_person_icon).error(R.mipmap.fill_person_icon)
                                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
                        ).into(iv_fill_information_icon);
//                        ToolUtils.showToast(Fill_Information_Activity.this, path);
                    } else {
                        ToolUtils.showToast(Fill_Information_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Fill_Information_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToolUtils.showToast(getApplicationContext(), "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                Utils.logOut2(Fill_Information_Activity.this);
                System.exit(0);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 网络请求
     */
    private void postOutLoginData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.out_login_Url + access_token, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("register", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {

                    } else {
                        ToolUtils.showToast(Fill_Information_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Fill_Information_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }
}
